﻿
namespace Numbrella.Tracker.WebService.Implementation
{
    using System;
    using System.Linq;
    using Numbrella.Core;
    using Numbrella.Tracker.Data;

    public class AuthorizationService : IAuthorizationService
    {
        public UserToken Login(string username, string password)
        {
            using (Data.TrackerEntities entities = new Data.TrackerEntities())
            {
                var users = from u in entities.Users
                            where u.Name == username
                            select u;

                if (users.Count() > 0 && users.First().Password == Utils.GetHashCode(password))
                {
                    User currentUser = users.First();

                    var tokenQuery = from t in entities.Tokens
                                     where t.User.Name == username
                                     select t;
                     
                    if (tokenQuery.Count() > 0)
                    {
                        entities.DeleteObject(tokenQuery.First());                        
                    }

                    Token token = Token.CreateToken(GenerateTokenID());
                    token.GivenTime = DateTime.Now;
                    entities.AddToTokens(token);
                    token.User = currentUser;

                    entities.SaveChanges();
                    return new UserToken { TokenID = token.ID, Username = currentUser.Name };
                }

                return null;
            }   
        }

        private static string GenerateTokenID()
        {
            // TODO: Correct id generation.
            return Utils.GetHashCode(DateTime.Now.ToString());
        }
    }
}
